class RatingsController < ApplicationController
  before_filter :ratings_management_access
  before_filter :get_target
  before_filter :target_should_not_be_owned_user
  before_filter :get_or_create_rating_mark_for_target

  def up
    if @rating.up
      @target.reload
      @success = t('rating.up.success')
    else
      @error = t('rating.up.error')
    end
  end

  def down
    if @rating.down
      @target.reload
      @success = t('rating.down.success')
    else
      @error = t('rating.down.error')
    end
  end

  protected
    def ratings_management_access
      check_access :rating
    end

    def get_target
      @target = case params[:target]
        when 'document'   then Document.find(params[:id])
        when 'comment'    then Comment.find(params[:id])
      end
    end

    def target_should_not_be_owned_user
      if @target.user == current_user
        @error = t('rating.access.error.target_should_not_be_owned_user')
        render :up and return
      end
    end

    def get_or_create_rating_mark_for_target
      # TODO move to model?
      @rating = RatingMark.find_or_initialize_by_user_id_and_target_type_and_target_id(
          current_user.id, params[:target].capitalize, params[:id]
      )
    end
end
